package com.socketeg.demo.myThread;

import com.socketeg.demo.socket.ManagerClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;


/**
 * 服务端线程
 */
public class ServerThread extends Thread {
    private Socket client;

    public ServerThread(Socket socket) {
        this.client = socket;
    }

    @Override
    public void run() {
        System.out.println("客户端：" + client.getInetAddress() + ":" + client.getPort() + "  建立了链接");
        ManagerClient.setClient(client.getInetAddress() + ":" + client.getPort(), client);
        try {
            // 输入流 用于接收数据
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            Readmessage readmessage = new Readmessage(bufferedReader);
            readmessage.start();
        } catch (Exception e) {
            System.out.println("客户端：：" + client.getInetAddress() + ":" + client.getPort() + "连接异常，将关闭连接");
            try {
                client.close();
                ManagerClient.removeClient(client.getInetAddress() + ":" + client.getPort());
                System.out.println("客户端异常，已退出");
            } catch (IOException ex) {
                System.out.println(ex.getMessage());
            }
        }
    }
}
